package org.cresource.org.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.cresource.basic.util.AjaxResult;
import org.cresource.basic.util.PageList;
import org.cresource.org.domain.Employee;
import org.cresource.org.query.EmployeeQuery;
import org.cresource.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 写接口
 */
@RequestMapping("/employee")
@RestController//返回数据格式为json是@Controller+@ResponseBody
@Api(tags = "员工接口",description = "员工接口详细描述")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    //新增或修改 @PutMapping

    /**
     * @RequestBody 我们从请求体中拿数据
     * @param employee
     */
    @PutMapping
    @ApiOperation(value = "员工添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
            try {
                if(employee.getId() == null){
                    employeeService.add(employee);
                }else {
                    employeeService.update(employee);
                }
                return AjaxResult.me();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.me().setMessage("系统繁忙，稍后重试!!!"+e.getMessage());
            }
    }
    //查询一条数据 @GetMapping
    @GetMapping("/{id}")
    @ApiOperation(value = "查询一条员工数据",notes = "通过id查询")
    public Employee getById(@PathVariable("id") Long id){
        return employeeService.getById(id);
    }
    //删除一条数据 @DeleteMapping
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一条员工数据",notes = "通过id删除")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙，稍后重试!!!"+e.getMessage());
        }
    }
    //分页查询 @PostMapping
    @PostMapping
    @ApiOperation(value = "分页查询",notes = "通过PageList进行分页")
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery employeeQuery){
        return employeeService.queryPage(employeeQuery);
    }

    /**
     * 如果前端传入数组，后端用list接收
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids) {
        try {
             employeeService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败"+e.getMessage());
        }
    }

    /**查询所有
     *
     */
    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<Employee> getAll(){
        return employeeService.getAll();
    }
}
